package com.ruoyi.ruoyiqywechat.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.qy.constants.Constants;
import com.ruoyi.common.qy.constants.WeChatConstants;
import com.ruoyi.common.qy.domain.User;
import com.ruoyi.common.qy.domain.UserToken;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.request.RegisterThirdUserRequest;
import com.ruoyi.common.qy.request.WxBindingPhoneRequest;
import com.ruoyi.common.qy.response.LoginResponse;
import com.ruoyi.common.qy.token.WeChatOauthToken;
import com.ruoyi.common.qy.utils.*;
import com.ruoyi.common.qy.vo.VideoInfoVo;
import com.ruoyi.common.qy.vo.WeChatAuthorizeLoginUserInfoVo;
import com.ruoyi.common.qy.vo.WeChatMiniAuthorizeVo;
import com.ruoyi.common.redis.utils.FrontTokenComponent;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.ruoyiqywechat.dao.UserDao;
import com.ruoyi.ruoyiqywechat.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户中心 服务实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class UserCenterServiceImpl extends ServiceImpl<UserDao, User> implements UserCenterService {

    private final Logger logger = LoggerFactory.getLogger(UserCenterServiceImpl.class);
    @Autowired
    private WechatNewService wechatNewService;
    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private UserService userService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SCRMUtils scrmUtils;
    @Autowired
    private CrmebUtil crmebUtil;

    /**
     * 小程序登录
     *
     * @param code    String 前端临时授权code
     * @param request RegisterThirdUserRequest 用户信息
     * @return LoginResponse
     */
    @Override
    public LoginResponse weChatAuthorizeProgramLogin(String code, RegisterThirdUserRequest request) {
        WeChatMiniAuthorizeVo response = wechatNewService.miniAuthCode(code);
        System.out.println("小程序登陆成功 = " + JSON.toJSONString(response));

        //检测旧用户的openId是否存在
        UserToken userTokenOpenId = userTokenService.getByOpenidAndType(response.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC);
        //同时检测unionid是否存在(小程序+公众号的公用)
        UserToken userTokenUnionId = userTokenService.getByOpenidAndType(response.getUnionId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC);
        LoginResponse loginResponse = new LoginResponse();
        UserToken userToken;
        if (Optional.ofNullable(userTokenOpenId).isPresent() || Optional.ofNullable(userTokenUnionId).isPresent()) {// 两个其中一个存在已存在，正常登录
            if(ObjectUtil.isNotNull(userTokenOpenId)){
                userToken = userTokenOpenId;
            }else{
                userToken = userTokenUnionId;
            }

            User user = userService.getById(userToken.getUid());
            if (!user.getStatus()) {
                throw new CrmebException("当前账户已禁用，请联系管理员！");
            }
            // 记录最后一次登录时间
            user.setLastLoginTime(DateUtils.getNowDate());
            Boolean execute = transactionTemplate.execute(e -> {
                // 分销绑定

                if(user.getSpreadUid() != null && user.getSpreadUid() != 0 && request.getSpreadPid() != null && request.getSpreadPid() != 0 &&  user.getSpreadUid().compareTo(request.getSpreadPid()) != 0){
                    throw new CrmebException("已绑定其他分享者用户ID~");
                }
                //判断是否已经存在了绑定关系
                if(request.getSpreadPid() != null && user.getUid().compareTo(request.getSpreadPid()) ==0){
                    throw new CrmebException("未识别好友分享码!");
                }
                if(request.getSpreadPid() != null && request.getSpreadPid() != 0){
                    user.setSpreadUid(request.getSpreadPid());
                    user.setSpreadTime(DateUtils.getNowDate());
                }
                user.setUpdateTime(DateUtils.getNowDate());
                user.setMark(response.getOpenId());//openId
                user.setAccount(response.getUnionId());
                userService.updateById(user);
                if(ObjectUtil.isNotNull(userTokenOpenId)){
                    userTokenService.updateUnionByUid(response.getOpenId(),response.getUnionId(),Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC,user.getUid());
//                    userTokenService.bind(response.getUnionId(),1,user.getUid());
                }



                //绑定对应的用户以及对应的视频从redis中绑定关系
                String key = CacheConstants.VIDEO_CREATE_USER + user.getUid();


                //获取对应视频的信息
                if(StringUtils.isNotBlank(request.getSpreadVideoId())){
                    Object o = redisUtil.get(CacheConstants.TEMP_VIDEO_CREATE_USER+request.getSpreadVideoId());
                    System.out.println("redis中的数据：" + request.getSpreadVideoId() + " --- " + o);
                    if (o != null) {
                        VideoInfoVo videoInfo = null;
                        try {
                            videoInfo = JSONObject.parseObject(o.toString(), VideoInfoVo.class);
                            // 使用 videoInfo 对象
                        } catch (Exception ex) {
                            // 处理异常或返回默认值
                        }
                        if (videoInfo != null) {
                            redisUtil.zAdd(key, videoInfo.getId(), videoInfo.getCreateDateTime());
                            // 存储到 Redis 时，确保生成有效的 JSON
                            String videoJSON = JSONObject.toJSONString(videoInfo);
                            // 检查并修复 JSON 格式
                            videoJSON = videoJSON.replace("\n", "").replace("\r", ""); // 移除换行符
                            redisUtil.hset(CacheConstants.VIDEO_HASH_USER+user.getUid(),request.getSpreadVideoId(),videoJSON);
                        }
                    }else{
                        System.out.println("视频过期了..");
                    }

                }

                return Boolean.TRUE;
            });
            if (!execute) {
                logger.error(StringUtils.format("小程序登录绑定分销关系失败，uid={},spreadUid={}", user.getUid(), request.getSpreadPid()));
            }

            try {
                String token = tokenService.createToken(user);
                System.out.println("当前的token"+token);
                loginResponse.setToken(token);
            } catch (Exception e) {
                logger.error(StrUtil.format("小程序登录生成token失败，uid={}", user.getUid()));
                e.printStackTrace();
            }
            loginResponse.setType("login");
            loginResponse.setUid(user.getUid());
            loginResponse.setNikeName(user.getNickname());
            loginResponse.setPhone(user.getPhone());
            return loginResponse;
        }

//        if (StringUtils.isBlank(request.getNickName()) && StringUtils.isBlank(request.getAvatar()) && StringUtils.isBlank(request.getHeadimgurl())) {
//            // 返回后，前端去走注册起始页
//            loginResponse.setType("start");
//            return loginResponse;
//        }
        if (StringUtils.isBlank(request.getNickName())) {
            request.setNickName("力推视频号助手");
        }else if(request.getNickName().equals("普通用户")){
            request.setNickName("力推视频号助手");
        }
        //判断数据库是否存在openId，存在则
        request.setType(Constants.USER_LOGIN_TYPE_PROGRAM);
        request.setOpenId(response.getOpenId());
        request.setUnionId(response.getUnionId());
        String key = SecureUtil.md5(response.getUnionId());
        redisUtil.set(key, JSONObject.toJSONString(request), (long) (60 * 2), TimeUnit.MINUTES);
        loginResponse.setType("register");
        loginResponse.setKey(key);

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getAccount,response.getUnionId());
        User user = userService.getOne(userQueryWrapper);
        if(user == null){
             user = new User();
            user.setAccount(response.getUnionId());
            System.out.println("当前值："+response.getSessionKey());
            user.setNickname("力推视频助手");
            user.setMark(response.getOpenId());
            userService.saveOrUpdate(user);
            loginResponse.setUid(user.getUid());
            String token = tokenService.createToken(user);
            System.out.println("当前的token"+token);
            loginResponse.setToken(token);
            userTokenService.bind(response.getUnionId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC, user.getUid());
        }else{
            loginResponse.setUid(user.getUid());
            String token = tokenService.createToken(user);
            System.out.println("当前的token"+token);
            loginResponse.setToken(token);
        }

        System.out.println("当前是否存在分享好友的二维码信息："+request.getSpreadPid());
        System.out.println("用户信息："+user);
            // 分销绑定

            if(user.getSpreadUid() != null && user.getSpreadUid() != 0 && request.getSpreadPid() != null && request.getSpreadPid() != 0 && user.getSpreadUid().compareTo(request.getSpreadPid()) != 0){
                throw new CrmebException("已绑定其他分享者用户ID~");
            }
        //判断是否已经存在了绑定关系
        if(request.getSpreadPid() != null && user.getUid().compareTo(request.getSpreadPid()) ==0){
            throw new CrmebException("未识别好友分享码!");
        }
        if(request.getSpreadPid() != null && request.getSpreadPid() != 0){
            user.setSpreadUid(request.getSpreadPid());
            user.setSpreadTime(DateUtils.getNowDate());
        }

            user.setUpdateTime(DateUtils.getNowDate());
        user.setMark(response.getOpenId());//openId
            userService.updateById(user);

            //绑定对应的用户以及对应的视频从redis中绑定关系
            key = CacheConstants.VIDEO_CREATE_USER + user.getUid();


            //获取对应视频的信息
            if(StringUtils.isNotBlank(request.getSpreadVideoId())){
                Object o = redisUtil.get(CacheConstants.TEMP_VIDEO_CREATE_USER+request.getSpreadVideoId());
                System.out.println("redis中的数据：" + request.getSpreadVideoId() + " --- " + o);
                if (o != null) {
                    VideoInfoVo videoInfo = null;
                    try {
                        videoInfo = JSONObject.parseObject(o.toString(), VideoInfoVo.class);
                        // 使用 videoInfo 对象
                    } catch (Exception ex) {
                        // 处理异常或返回默认值
                    }
                    if (videoInfo != null) {
                        redisUtil.zAdd(key, videoInfo.getId(), videoInfo.getCreateDateTime());
                        // 存储到 Redis 时，确保生成有效的 JSON
                        String videoJSON = JSONObject.toJSONString(videoInfo);
                        // 检查并修复 JSON 格式
                        videoJSON = videoJSON.replace("\n", "").replace("\r", ""); // 移除换行符
                        redisUtil.hset(CacheConstants.VIDEO_HASH_USER+user.getUid(),request.getSpreadVideoId(),videoJSON);
                    }
                }else{
                    System.out.println("视频过期了..");
                }
            }
        return loginResponse;
    }


    /**
     * 微信注册绑定手机号
     *
     * @param request 请求参数
     * @return 登录信息
     */
    @Override
    public LoginResponse registerBindingPhone(WxBindingPhoneRequest request) {
        checkBindingPhone(request);

        // 进入创建用户绑定手机号流程
        Object o = redisUtil.get(request.getKey());
        if (ObjectUtil.isNull(o)) {
            throw new CrmebException("用户缓存已过期，请清除缓存重新登录");
        }
        RegisterThirdUserRequest registerThirdUserRequest = JSONObject.parseObject(o.toString(), RegisterThirdUserRequest.class);

        boolean isNew = true;

        User user = userService.getByPhone(request.getPhone());
        if (ObjectUtil.isNull(user)) {
            user = userService.registerByThird(registerThirdUserRequest);
            user.setPhone(request.getPhone());
            user.setAccount(request.getPhone());
            user.setSpreadUid(0);
            user.setPwd(CommonUtil.createPwd(request.getPhone()));
        } else {// 已有账户，关联到之前得账户即可
            // 查询是否用对应得token
            int type = 0;
            switch (request.getType()) {
                case "public":
                    type = Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC;
                    break;
                case "routine":
                    type = Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM;
                    break;
                case "iosWx":
                    type = Constants.THIRD_LOGIN_TOKEN_TYPE_IOS_WX;
                    break;
                case "androidWx":
                    type = Constants.THIRD_LOGIN_TOKEN_TYPE_ANDROID_WX;
                    break;
            }

            UserToken userToken = userTokenService.getTokenByUserId(user.getUid(), type);
            if (ObjectUtil.isNotNull(userToken)) {
                throw new CrmebException("该手机号已被注册");
            }
            isNew = false;
        }

        User finalUser = user;
        boolean finalIsNew = isNew;
        Boolean execute = transactionTemplate.execute(e -> {
            if (finalIsNew) {// 新用户
                // 分销绑定
//                if (userService.checkBingSpread(finalUser, registerThirdUserRequest.getSpreadPid(), "new")) {
//                    finalUser.setSpreadUid(registerThirdUserRequest.getSpreadPid());
//                    finalUser.setSpreadTime(CrmebDateUtil.nowDateTime());
//                    userService.updateSpreadCountByUid(registerThirdUserRequest.getSpreadPid(), "add");
//                }
                //绑定对应的用户以及对应的视频从redis中绑定关系
                String key = CacheConstants.VIDEO_CREATE_USER + finalUser.getUid();
                //获取对应视频的信息
                Object ox = redisUtil.get(CacheConstants.TEMP_VIDEO_CREATE_USER+registerThirdUserRequest.getSpreadVideoId());
                System.out.println("绑定手机号redis中的数据：" + registerThirdUserRequest.getSpreadVideoId() + " --- " + ox);
                if (ox != null) {
                    VideoInfoVo videoInfo = null;
                    try {
                        videoInfo = JSONObject.parseObject(ox.toString(), VideoInfoVo.class);
                        // 使用 videoInfo 对象
                    } catch (Exception ex) {
                        // 处理异常或返回默认值
                    }
                    if (videoInfo != null) {
                            redisUtil.zAdd(key, videoInfo.getId(),  videoInfo.getCreateDateTime());
                            // 存储到 Redis 时，确保生成有效的 JSON
                            String videoJSON = JSONObject.toJSONString(videoInfo);
                            // 检查并修复 JSON 格式
                            videoJSON = videoJSON.replace("\n", "").replace("\r", ""); // 移除换行符
                            redisUtil.hset(CacheConstants.VIDEO_HASH_USER+finalUser.getUid(),registerThirdUserRequest.getSpreadVideoId(),videoJSON);
                        userService.save(finalUser);
                    }
                }
                // 赠送新人券
//                giveNewPeopleCoupon(finalUser.getUid());
            }
            switch (request.getType()) {
                case "public":
                    userTokenService.bind(registerThirdUserRequest.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC, finalUser.getUid());
                    break;
                case "routine":
                    userTokenService.bind(registerThirdUserRequest.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM, finalUser.getUid());
                    break;
                case "iosWx":
                    userTokenService.bind(registerThirdUserRequest.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_IOS_WX, finalUser.getUid());
                    break;
                default:
                    userTokenService.bind(registerThirdUserRequest.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_ANDROID_WX, finalUser.getUid());
                    break;
            }
            return Boolean.TRUE;
        });
        if (!execute) {
            logger.error("微信用户注册生成失败，nickName = " + registerThirdUserRequest.getNickName());
        } else if (!isNew) {// 老用户绑定   if (ObjectUtil.isNotNull(registerThirdUserRequest.getSpreadPid()) && registerThirdUserRequest.getSpreadPid() > 0) {
//                loginService.bindSpread(finalUser, registerThirdUserRequest.getSpreadPid());
//            }推广人
//
        }
        LoginResponse loginResponse = new LoginResponse();
        try {
            String token = tokenService.createToken(finalUser);
            loginResponse.setToken(token);
        } catch (Exception e) {
            logger.error(StrUtil.format("绑定手机号，自动登录生成token失败，uid={}", finalUser.getUid()));
            e.printStackTrace();
        }
        loginResponse.setType("login");
        loginResponse.setUid(user.getUid());
        loginResponse.setNikeName(user.getNickname());
        loginResponse.setPhone(user.getPhone());
        try {
            scrmUtils.addUserForSCRM(user.getPhone(), user.getNickname());
        } catch (Exception e) {
            logger.error("SCRM用户同步失败: phone={}, nickname={}", user.getPhone(), user.getNickname(), e);
        }
        return loginResponse;
    }

    /**
     * 微信登录
     *
     * @return LoginResponse;
     */
    @Override
    public LoginResponse weChatAuthorizeLogin(String code,String sendUserId) {
        if (ObjectUtil.isNull(sendUserId)) {
            throw new CrmebException("sendUserId不允许为空");
        }
        // 通过code获取获取公众号授权信息
        WeChatOauthToken oauthToken = wechatNewService.getOauth2AccessToken(code);
        //检测是否存在
        UserToken userTokenOpenId = userTokenService.getByOpenidAndType(oauthToken.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC);
        UserToken userTokenUnionId = userTokenService.getByOpenidAndType(oauthToken.getUnionId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC);
        UserToken userToken ;
        LoginResponse loginResponse = new LoginResponse();
        if (ObjectUtil.isNotNull(userTokenOpenId) || ObjectUtil.isNotNull(userTokenUnionId)) {// 已存在，正常登录
            if(ObjectUtil.isNotNull(userTokenOpenId)){
                userToken = userTokenOpenId;
            }else{
                userToken = userTokenUnionId;
            }

            User user = userService.getById(userToken.getUid());
            if (!user.getStatus()) {
                throw new CrmebException("当前账户已禁用，请联系管理员！");
            }
            if(ObjectUtil.isNull(user.getTagId()) || "".equals(user.getTagId()) || "0".equals(user.getTagId())){
                user.setTagId(sendUserId);//绑定微信标签
            }

            // 记录最后一次登录时间
            user.setLastLoginTime(CrmebDateUtil.nowDateTime());
            user.setBirthday(oauthToken.getOpenId());//openId
            try {
                String token = tokenService.createToken(user);
                loginResponse.setToken(token);
            } catch (Exception e) {
                logger.error(StrUtil.format("公众号登录生成token失败，uid={}", user.getUid()));
                e.printStackTrace();
            }
            loginResponse.setType("login");
            loginResponse.setUid(user.getUid());
            loginResponse.setNikeName(user.getNickname());
            loginResponse.setPhone(user.getPhone());

            loginResponse.setMemberFlag(user.getIsFenjian());

            user.setAccount(oauthToken.getUnionId());
            userService.updateById(user);
            if(ObjectUtil.isNotNull(userTokenOpenId)){
                userTokenService.updateUnionByUid(oauthToken.getOpenId(),oauthToken.getUnionId(),Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC,user.getUid());
//                userTokenService.bind(oauthToken.getUnionId(),1,user.getUid());
            }

            return loginResponse;
        }
        // 没有用户，走创建用户流程
        // 从微信获取用户信息，存入Redis中，将key返回给前端，前端在下一步绑定手机号的时候下发
        WeChatAuthorizeLoginUserInfoVo userInfo = wechatNewService.getSnsUserInfo(oauthToken.getAccessToken(), oauthToken.getOpenId());
        RegisterThirdUserRequest registerThirdUserRequest = new RegisterThirdUserRequest();
        BeanUtils.copyProperties(userInfo, registerThirdUserRequest);
//        registerThirdUserRequest.setSpreadPid(spreadUid);
        registerThirdUserRequest.setType(Constants.USER_LOGIN_TYPE_PUBLIC);
        registerThirdUserRequest.setOpenId(oauthToken.getOpenId());
        registerThirdUserRequest.setUnionId(oauthToken.getUnionId());
        String key = SecureUtil.md5(oauthToken.getUnionId());
        redisUtil.set(key, JSONObject.toJSONString(registerThirdUserRequest), (long) (60 * 2), TimeUnit.MINUTES);

        loginResponse.setType("register");
        loginResponse.setKey(key);

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getAccount,oauthToken.getUnionId());
        User user = userService.getOne(userQueryWrapper);
        if(user == null){
            user = new User();
            user.setAccount(oauthToken.getUnionId());
            System.out.println("h5OpenId当前值："+oauthToken.getOpenId());
            System.out.println("h5UnionId当前值："+oauthToken.getUnionId());
            user.setNickname("力推视频助手");
            user.setBirthday(oauthToken.getOpenId());
            if(ObjectUtil.isNull(user.getTagId()) || "".equals(user.getTagId()) || "0".equals(user.getTagId())){
                user.setTagId(sendUserId);//绑定微信标签
            }
            userService.saveOrUpdate(user);
            loginResponse.setUid(user.getUid());
            String token = tokenService.createToken(user);
            System.out.println("当前的token"+token);
            loginResponse.setToken(token);
            userTokenService.bind(oauthToken.getUnionId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC, user.getUid());
        }else{
            loginResponse.setUid(user.getUid());
            String token = tokenService.createToken(user);
            System.out.println("当前的token"+token);
            loginResponse.setToken(token);
            if(ObjectUtil.isNull(user.getTagId()) || "".equals(user.getTagId()) || "0".equals(user.getTagId())){
                user.setTagId(sendUserId);//绑定微信标签
                userService.saveOrUpdate(user);
            }
        }
        loginResponse.setMemberFlag(user.getIsFenjian());
        return loginResponse;
    }
    /**
     * 通过微信信息注册用户
     *
     * @param thirdUserRequest RegisterThirdUser 三方用户登录注册信息
     * @return User
     */
    @Override
    public User registerByThird(RegisterThirdUserRequest thirdUserRequest) {
        User user = new User();
        user.setAccount(DigestUtils.md5Hex(CrmebUtil.getUuid() + DateUtils.getNowDate()));
        user.setUserType(thirdUserRequest.getType());
        user.setNickname(thirdUserRequest.getNickName());
        String avatar = "";
        switch (thirdUserRequest.getType()) {
            case Constants.USER_LOGIN_TYPE_PUBLIC:
                avatar = StrUtil.isBlank(thirdUserRequest.getHeadimgurl()) ? "" : thirdUserRequest.getHeadimgurl();
                break;
            case Constants.USER_LOGIN_TYPE_PROGRAM:
            case Constants.USER_LOGIN_TYPE_H5:
            case Constants.USER_LOGIN_TYPE_IOS_WX:
            case Constants.USER_LOGIN_TYPE_ANDROID_WX:
                avatar = StrUtil.isBlank(thirdUserRequest.getAvatar()) ? "" : thirdUserRequest.getAvatar();
                break;
        }
        user.setAvatar(avatar);
        user.setSpreadTime(DateUtils.getNowDate());
        // 因微信原因，无法再获取用户的隐私信息
        // 预设用户性别为0-未知，地址为空字符串
//        user.setSex(Integer.parseInt(thirdUserRequest.getSex()));
//        user.setAddres(thirdUserRequest.getCountry() + "," + thirdUserRequest.getProvince() + "," + thirdUserRequest.getCity());
        user.setSex(0);
        user.setAddres("");
        return user;
    }

    @Autowired
    private SystemConfigService systemConfigService;

    /**
     * 绑定手机号数据校验
     */
    private void checkBindingPhone(WxBindingPhoneRequest request) {
        // 参数校验
        if (StrUtil.isBlank(request.getCode())) {
            throw new CrmebException("小程序获取手机号code不能为空");
        }
        if (StrUtil.isBlank(request.getEncryptedData())) {
            throw new CrmebException("小程序获取手机号加密数据不能为空");
        }
        if (StrUtil.isBlank(request.getIv())) {
            throw new CrmebException("小程序获取手机号加密算法的初始向量不能为空");
        }
        // 获取appid
        String programAppId = systemConfigService.getValueByKey(WeChatConstants.WECHAT_MINI_APPID);
        if (StrUtil.isBlank(programAppId)) {
            throw new CrmebException("微信小程序appId未设置");
        }

        WeChatMiniAuthorizeVo response = wechatNewService.miniAuthCode(request.getCode());
        System.out.println("小程序登陆成功 = " + JSON.toJSONString(response));
        String decrypt = WxUtil.decrypt(programAppId, request.getEncryptedData(), response.getSessionKey(), request.getIv());
        if (StrUtil.isBlank(decrypt)) {
            throw new CrmebException("微信小程序获取手机号解密失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        if (StrUtil.isBlank(jsonObject.getString("phoneNumber"))) {
            throw new CrmebException("微信小程序获取手机号没有有效的手机号");
        }
        request.setPhone(jsonObject.getString("phoneNumber"));
    }
}
